package com.fishingwithme.infrastructure;

import com.fishingwithme.infrastructure.dtos.DTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import com.fishingwithme.infrastructure.utils.ObjectMapperFactory;

import java.io.IOException;


public class WeChatLoginFailureHandler implements AuthenticationFailureHandler {
    @Autowired
    private ObjectMapperFactory factory;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        DTO<Boolean> dto = DTO.fail(Boolean.FALSE,401,"认证失败: " + exception.getMessage());
        ObjectMapper mapper = factory.getInstance();
        mapper.writeValue(response.getWriter(), dto);
    }
}
